package nonthreaded;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import utility.Keyword;

/**
 * Normal version of the page analyzer.
 * Provides utility for analyzing a pages html document source
 * and keeps track of stats about past pages.
 * @author Daniel Anderson and Luc H. Le
 * @version TCSS422 2012
 */
public class PageAnalyzer {
	
	/**List of keywords to scan the page for.*/
	List<Keyword> my_keywords;
	
	/**Current page passed for analyzing.*/
	String my_page; 
	
	/**Number of pages analyzed so far.*/
	int my_page_count;
	
	/**Number of words scanned so far.*/
	int my_word_count;
	
	/**Number of pages scanned so far.*/
	int my_url_count;
	
	/**Constructor for PageAnalyzer.*/
	public PageAnalyzer() {
		my_keywords = new ArrayList<Keyword>();
		my_page = "";
		my_page_count = 0;
		my_word_count = 0;
		my_url_count = 0;
	}//end of constr

	/**
	 * Scans the text on the page for keywords and sets the classes current target.
	 * @param page The page to be analyzed.
	 * @param url_count The number of urls.
	 */
	public void analyzePage(String page, int url_count) {
		my_page = page;
		my_url_count = my_url_count + url_count;
		my_page_count++;
		tokenizeScan();
	}//end of analyzePage
	
	/**
	 * Adds a keyword to those to be scanned for.
	 * @param word The keyword.
	 */
	public void addKeyword(String word) {
		Keyword k = new Keyword(word);
		my_keywords.add(k);
	}//end of addKeyword
	
	/**
	 * Checks if my_keywords contains the keyword k, then if it does
	 * we find the index of key, and get the element at that index.
	 * We then call addHit() on that element.
	 * @param word The word to be checked.
	 */
	private void checkKeyword(String word) {
		for (int i = 0; i < my_keywords.size(); i++) {
			if(my_keywords.get(i).isWord(word)) {
				my_keywords.get(i).addHit();
			}
		}
	}//end of checkKeyword
	
	/**Tokenizes the text from the page, and scans each token for keywords.*/
	private void tokenizeScan() {
		StringTokenizer t = new StringTokenizer(my_page);
		while (t.hasMoreTokens()) {
			checkKeyword(t.nextToken());
			my_word_count++;
		}
	}//end of tokenizeScan
	
	/**
	 * Gets the stats of a certain keyword.
	 * @param word The keyword.
	 * @return Stats on that keyword.
	 */
	public Keyword getStats(String word) {
		Keyword key = new Keyword(word);
		for( Keyword k : my_keywords) {
			if(k.getWord().equals(word)) {
				key = k;
			}
		}
		return key;
	}//end of getStats
	
	/**Get method for number of words counted so far*/
	public int getWordCount() {
		return my_word_count;
	}//end of getWordCount
	
	/**Get method for number of urls counted so far*/
	public int getNumURLs() {
		return my_url_count;
	}//end of getNumURLs
	
	/**Returns number of pages counted so far.*/
	public int getNumPages() {
		return my_page_count;
	}//end of getNumPages
}//end of PageAnalyzer